"""
API网关服务依赖注入模块
========================

提供API网关服务实例的依赖注入功能
基于RedFire框架的统一架构
"""
import logging
from typing import Optional
from fastapi import Depends

# RedFire框架导入
from redfire_framework.core.container import RedFireContainer
from .config import get_api_gateway_config
from .services.gateway_service import GatewayService
from .services.route_service import RouteService
from .services.load_balancer_service import LoadBalancerService
# 移除冗余的监控服务导入 - 将使用框架标准功能
# from .services.health_check_service import GatewayHealthCheckService
# from .services.metrics_service import GatewayMetricsService

logger = logging.getLogger(__name__)

# 全局服务实例
_gateway_service: Optional[GatewayService] = None
_route_service: Optional[RouteService] = None
_load_balancer_service: Optional[LoadBalancerService] = None
# 移除冗余的监控服务实例 - 将使用框架标准功能
# _health_check_service: Optional[GatewayHealthCheckService] = None
# _metrics_service: Optional[GatewayMetricsService] = None
_container: Optional[RedFireContainer] = None


async def get_container() -> RedFireContainer:
    """
    获取API网关容器实例
    
    Returns:
        RedFireContainer: 容器实例
    """
    global _container
    
    if _container is None:
        try:
            # 获取API网关配置
            config = get_api_gateway_config()
            
            # 创建容器
            _container = RedFireContainer.create_for_service("api_gateway", config)
            
            logger.info("API Gateway container initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize API Gateway container: {e}", exc_info=True)
            raise
    
    return _container


async def get_gateway_service() -> GatewayService:
    """
    获取网关服务实例
    
    Returns:
        GatewayService: 网关服务实例
    """
    global _gateway_service
    
    if _gateway_service is None:
        try:
            container = await get_container()
            
            # 获取依赖
            cache_service = container.cache_service()
            event_bus = container.event_bus()
            middleware_manager = container.middleware_manager()
            
            # 获取API网关配置
            api_config = get_api_gateway_config()
            
            # 创建服务实例
            _gateway_service = GatewayService(
                cache_service=cache_service,
                event_bus=event_bus,
                middleware_manager=middleware_manager,
                config=api_config.dict()
            )
            
            logger.info("Gateway service initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize gateway service: {e}", exc_info=True)
            raise
    
    return _gateway_service


async def get_route_service() -> RouteService:
    """
    获取路由服务实例
    
    Returns:
        RouteService: 路由服务实例
    """
    global _route_service
    
    if _route_service is None:
        try:
            container = await get_container()
            
            # 获取依赖
            cache_service = container.cache_service()
            event_bus = container.event_bus()
            
            # 获取API网关配置
            api_config = get_api_gateway_config()
            
            # 创建服务实例
            _route_service = RouteService(
                cache_service=cache_service,
                event_bus=event_bus,
                config=api_config.dict()
            )
            
            logger.info("Route service initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize route service: {e}", exc_info=True)
            raise
    
    return _route_service


async def get_load_balancer_service() -> LoadBalancerService:
    """
    获取负载均衡服务实例
    
    Returns:
        LoadBalancerService: 负载均衡服务实例
    """
    global _load_balancer_service
    
    if _load_balancer_service is None:
        try:
            container = await get_container()
            
            # 获取依赖
            cache_service = container.cache_service()
            event_bus = container.event_bus()
            
            # 获取API网关配置
            api_config = get_api_gateway_config()
            
            # 创建服务实例
            _load_balancer_service = LoadBalancerService(
                cache_service=cache_service,
                event_bus=event_bus,
                config=api_config.dict()
            )
            
            logger.info("Load balancer service initialized successfully")
            
        except Exception as e:
            logger.error(f"Failed to initialize load balancer service: {e}", exc_info=True)
            raise
    
    return _load_balancer_service


# 移除冗余的监控服务函数 - 将使用框架标准功能
# async def get_health_check_service() -> GatewayHealthCheckService:
# async def get_metrics_service() -> GatewayMetricsService:


def reset_services():
    """重置所有服务实例（主要用于测试）"""
    global _gateway_service, _route_service, _load_balancer_service, _container
    
    _gateway_service = None
    _route_service = None
    _load_balancer_service = None
    # 移除冗余的监控服务重置 - 将使用框架标准功能
    # _health_check_service = None
    # _metrics_service = None
    _container = None
